/*
 * @Author: your name
 * @Date: 2021-05-12 15:50:50
 * @LastEditTime: 2021-05-14 15:22:04
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \koa2-serve\middlewares\jwt.js
 */
const jwt = require("jsonwebtoken");
const { secret } = require("../config.js");

module.exports = async (ctx, next) => {
    const token = ctx.header.authorization;
    try {
        await next();
        if (token) {
            const decoded = jwt.verify(token.replace('Bearer ',''), secret.jwtKey);
            const _token = jwt.sign({
                userName:decoded.userName,
                id:decoded._id
            }, secret.jwtKey, { expiresIn:'1h' })
            ctx.append("token", 'Bearer '+_token);
        }
    } catch (error) {
        console.log("[tokenError] ", error.message);
        if (token) {
            if (error.originalError && error.originalError.message === "jwt expired") {
                return ctx.error({ error: "token过期", status: 200 });
            } else {
                return ctx.error({ error: "token无效", status: 200 });
            }
        } else {
            return ctx.error({ error: "token缺失", status: 200 });
        }
    }
};
